<?php
/**
 * Vendor2 MQTT 消息追踪调试脚本
 * 详细追踪数据流向
 */

// 定义应用根目录
define('APP_PATH', __DIR__ . '/application/');
define('RUNTIME_PATH', __DIR__ . '/runtime/');

require __DIR__ . '/thinkphp/base.php';

use think\Db;
use app\service\MqttMessageHandler;

echo "========== Vendor2 MQTT 消息追踪调试 ==========\n\n";

$topic = 'rziot/zftx_w06/861179035726231/result';
$messageData = [
    "c" => "zidianmao",
    "imei" => "861179035726231",
    "iccid" => "89860325247554801710",
    "ssid" => "MIFI-8915",
    "password" => "1234567890",
    "opname" => "46003",
    "dbm" => "-86",
    "simSwitch" => "2",
    "ip" => "192.168.100.1",
    "lac" => "30555",
    "version" => "JZ12SC_ZIDIANMAO_20251200_V1.0.0",
    "cell_id" => "27235605",
    "speed_downlink" => 0,
    "speed_uplink" => 0,
    "sn" => "86117903572623",
    "boot_time" => "1236643",
    "count" => "8",
    "hidden" => "0"
];

$imei = '861179035726231';

// 创建一个自定义的 MqttMessageHandler 来追踪
class TracingMqttMessageHandler extends MqttMessageHandler {
    public function getMessageBuffer() {
        return $this->messageBuffer;
    }
    
    public function saveToDatabase(): void {
        echo "【追踪】saveToDatabase() 被调用\n";
        echo "【追踪】缓冲区大小: " . count($this->messageBuffer) . "\n";
        
        if (!empty($this->messageBuffer)) {
            foreach ($this->messageBuffer as $index => $data) {
                echo "【追踪】缓冲区消息 {$index}: IMEI=" . ($data['IMEI'] ?? 'N/A') . "\n";
            }
        }
        
        parent::saveToDatabase();
        
        echo "【追踪】saveToDatabase() 完成\n";
        echo "【追踪】缓冲区大小(完成后): " . count($this->messageBuffer) . "\n";
    }
}

echo "【步骤1】创建处理器并处理消息\n";
$handler = new TracingMqttMessageHandler();
$result = $handler->handle($topic, $messageData);
echo "处理结果: " . ($result ? "成功" : "失败") . "\n";
echo "缓冲区大小: " . count($handler->getMessageBuffer()) . "\n\n";

echo "【步骤2】调用 flush() 保存到数据库\n";
$handler->flush();
echo "flush() 完成\n\n";

echo "【步骤3】直接查询数据库验证\n";
try {
    $record = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();
    if ($record) {
        echo "✅ 数据库中找到记录\n";
        echo "   IMEI: " . $record['IMEI'] . "\n";
        echo "   MAC: " . $record['mac'] . "\n";
        echo "   ICCID: " . $record['iccid'] . "\n";
        echo "   更新时间: " . $record['update_time'] . "\n";
    } else {
        echo "❌ 数据库中没有找到记录\n";
    }
} catch (\Throwable $e) {
    echo "❌ 查询失败: " . $e->getMessage() . "\n";
}

echo "\n========== 追踪完成 ==========\n";

